package com.ljx.designMode.agency;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2022/11/9 16:28
 * @Version 1.0
 */
public class JdkDynamicAgencyTest02 {
	public static void main(String[] args) {
		AgencyFactory agencyFactory = new AgencyFactory(new SimpleOperation());
		Operation instance = agencyFactory.getInstance();
		System.out.println(instance.add(10, 20));
		System.out.println(instance.jian(12, 23));
		System.out.println(instance.cheng(12,12));
		System.out.println(instance.chu(12,7));


	}
}

interface Operation{
	int add(int a,int b);
	int jian(int a,int b);
	int cheng(int a,int b);
	double chu(int a,int b);
}

class SimpleOperation implements Operation{
	@Override
	public int add(int a, int b) {
		return a+b;
	}

	@Override
	public int jian(int a, int b) {
		return a-b;
	}

	@Override
	public int cheng(int a, int b) {
		return a*b;
	}

	@Override
	public double chu(int a, int b) {
		return a/b;
	}
}

class AgencyFactory{
	private Operation target;

	public AgencyFactory(Operation target) {
		this.target = target;
	}
	/**
	 * 获取代理对象
	 */
	public Operation getInstance(){
		ClassLoader classLoader = target.getClass().getClassLoader();
		Class<?>[] interfaces = target.getClass().getInterfaces();
		InvocationHandler invocationHandler = new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object invoke = method.invoke(target,args);
				// 当我们调用被代理类方法有返回值的时候，一定要return 回调函数
				return invoke;
			}
		};
		Object o = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
		return (Operation) o;

	}

	public void A(){
		System.out.println("前置校验内容");
	}

	public void B(){
		System.out.println("添加校验内容");
	}
}